package com.onluy.frameworkcloud.tools;

 
import java.security.Key;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

public class DESEncoder {
	protected static Logger logger =   LoggerFactory.getLogger(DESEncoder.class);
	private static final String PUB_PASSWORD_KEY = "tbss@#12";
	private static Cipher encryptCipher = null;
	private static Cipher decryptCipher = null;
	private static Map<String, Cipher> decryptMap = new HashMap();
	private static Map<String, Cipher> encryptMap = new HashMap();

	static {
		try {
			Key e = getKey("tbss@#12".getBytes());
			encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(1, e);
			decryptCipher = Cipher.getInstance("DES");
			decryptCipher.init(2, e);
		} catch (Exception arg0) {
            logger.error(arg0.getMessage() );
		}

	}

	private static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		StringBuffer sb = new StringBuffer(iLen * 2);

		for (int i = 0; i < iLen; ++i) {
			int intTmp;
			for (intTmp = arrB[i]; intTmp < 0; intTmp += 256) {
				;
			}

			if (intTmp < 16) {
				sb.append("0");
			}

			sb.append(Integer.toString(intTmp, 16));
		}

		return sb.toString();
	}

	private static byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;
		byte[] arrOut = new byte[iLen / 2];

		for (int i = 0; i < iLen; i += 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}

		return arrOut;
	}

	public DESEncoder() throws Exception {
		this("tbss@#12");
	}

	public DESEncoder(String strKey) throws Exception {
		Key key = getKey(strKey.getBytes());
		encryptCipher = Cipher.getInstance("DES");
		encryptCipher.init(1, key);
		decryptCipher = Cipher.getInstance("DES");
		decryptCipher.init(2, key);
	}

	private static byte[] encrypt(byte[] arrB) throws Exception {
		try {
			return encryptCipher.doFinal(arrB);
		} catch (Exception arg3) {
			logger.error(arg3.getMessage());
			logger.info("异常后初始化加密对象。不然加密对象将无法使用");
			encryptCipher.init(1, getKey("tbss@#12".getBytes()));
			try {
				return encryptCipher.doFinal(arrB);
			} catch (Exception arg2) {
				throw arg2;
			}
		}
	}

	public static String encrypt(String strIn) throws Exception {
		return byteArr2HexStr(encrypt(strIn.getBytes()));
	}

	public static String encrypt(String strIn, String charset) throws Exception {
		return byteArr2HexStr(encrypt(strIn.getBytes(charset)));
	}

	private static byte[] decrypt(byte[] arrB) throws Exception {
		try {
			return decryptCipher.doFinal(arrB);
		} catch (Exception arg3) {
			logger.error(arg3.getMessage());
			logger.info("异常后初始化解密对象。不然加密对象将无法使用");
			decryptCipher.init(2, getKey("tbss@#12".getBytes()));

			try {
				return decryptCipher.doFinal(arrB);
			} catch (Exception arg2) {
				throw arg2;
			}
		}
	}

	public static String decrypt(String strIn) throws Exception {
		return new String(decrypt(hexStr2ByteArr(strIn)));
	}

	public static String decrypt(String strIn, String charset) throws Exception {
		return new String(decrypt(hexStr2ByteArr(strIn)), charset);
	}

	private static Key getKey(byte[] arrBTmp) throws Exception {
		byte[] arrB = new byte[8];

		for (int key = 0; key < arrBTmp.length && key < arrB.length; ++key) {
			arrB[key] = arrBTmp[key];
		}

		SecretKeySpec arg2 = new SecretKeySpec(arrB, "DES");
		return arg2;
	}

	public static String getSHA(String vars, String unicode) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance("SHA-1");
		md5.update(vars.getBytes(unicode));
		byte[] digesta = md5.digest();
		BASE64Encoder base64 = new BASE64Encoder();
		return base64.encode(digesta);
	}

	public static String getMD5(String vars, String unicode) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance("md5");
		md5.update(vars.getBytes(unicode));
		byte[] digesta = md5.digest();
		BASE64Encoder base64 = new BASE64Encoder();
		return base64.encode(digesta);
	}

	public static String decrypt(String content, String keyValue, String charset) throws Exception {
		byte[] array = hexStr2ByteArr(content);
		byte[] result = (byte[]) null;
		Cipher decrypt = CipherManage.getDecrypt(keyValue);
		CipherManage.getDecryptLock().readLock().lock();

		try {
			result = decrypt.doFinal(array);
			CipherManage.getDecryptLock().readLock().unlock();
		} catch (Exception arg13) {
			Exception e = arg13;
			logger.error(arg13.getMessage());
			CipherManage.getDecryptLock().readLock().unlock();
			CipherManage.removeDecrypt(keyValue);
			logger.info("解密失败，删除解密对象再次创建!" + arg13.getMessage());
			decrypt = CipherManage.getDecrypt(keyValue);
			CipherManage.getDecryptLock().readLock().lock();

			try {
				result = decrypt.doFinal(array);
			} catch (Exception arg11) {
				CipherManage.removeDecrypt(keyValue);
				logger.info("解密再次异常，删除保存的解密对象!" + e.getMessage());
				throw arg11;
			} finally {
				CipherManage.getDecryptLock().readLock().unlock();
			}
		}

		return new String(result, charset);
	}

	public static String encrypt(String content, String keyValue, String charset) throws Exception {
		byte[] arrB = content.getBytes(charset);
		Cipher encrypt = CipherManage.getEncrypt(keyValue);
		CipherManage.getEncrypLock().readLock().lock();

		try {
			String e = byteArr2HexStr(encrypt.doFinal(arrB));
			CipherManage.getEncrypLock().readLock().unlock();
			return e;
		} catch (Exception arg13) {
			logger.error(arg13.getMessage());
			CipherManage.getEncrypLock().readLock().unlock();
			CipherManage.removeEncrypt(keyValue);
			logger.info("加密异常，删除保存的加密对象!");
			encrypt = CipherManage.getEncrypt(keyValue);
			CipherManage.getEncrypLock().readLock().lock();

			String arg7;
			try {
				arg7 = byteArr2HexStr(encrypt.doFinal(arrB));
			} catch (Exception arg11) {
				CipherManage.removeEncrypt(keyValue);
				logger.info("加密再次异常，删除保存的加密对象!");
				throw arg11;
			} finally {
				CipherManage.getEncrypLock().readLock().unlock();
			}

			return arg7;
		}
	}

	public static void main(String[] args) {
		try {
			String e = "Rd520520";
			System.out.println("加密前的字符：" + e);
			System.out.println("加密后的字符：" + encrypt(e));
			System.out.println("解密后的字符：" + decrypt(encrypt(e)));
			System.out.println("加密后的字符：" + encrypt(e, "robot20160324", "UTF-8"));
			System.out.println("解密后的字符：" + decrypt(encrypt(e, "robot20160324", "UTF-8"), "robot20160324", "UTF-8"));
		} catch (Exception arg1) {
			logger.error(arg1.getMessage(), arg1);
			arg1.printStackTrace();
		}

	}
}